<script setup lang="ts">
import { ref, onMounted, nextTick, watch } from "vue";
import { useECharts } from "@pureadmin/utils";

const props = defineProps<{
  data: any[];
}>();

const chartRef = ref<HTMLDivElement>();
const { setOptions, resize, getInstance } = useECharts(chartRef);

const drawChart = () => {
  const departments = props.data.map((item) => item.department);
  const ipCounts = props.data.map((item) => item.ip_count);
  const portCounts = props.data.map((item) => item.port_count);

  setOptions({
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    legend: {
      data: ["IP数量", "端口数量"],
      top: 10,
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: departments,
      axisLabel: {
        rotate: 30,
      },
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "IP数量",
        type: "bar",
        data: ipCounts,
        itemStyle: { color: "#409EFF" },
      },
      {
        name: "端口数量",
        type: "bar",
        data: portCounts,
        itemStyle: { color: "#67C23A" },
      },
    ],
  });
};

onMounted(() => {
  nextTick(() => {
    drawChart();
    // 延迟调用 resize，确保图表已初始化
    setTimeout(() => {
      if (getInstance()) {
        resize();
      }
    }, 100);
  });
});

watch(() => props.data, drawChart, { deep: true });

defineExpose({ resize });
</script>

<template>
  <el-card shadow="hover">
    <template #header>
      <span class="card-title">部门分布统计 (Top 10)</span>
    </template>
    <div ref="chartRef" style="height: 300px"></div>
  </el-card>
</template>

<style lang="scss" scoped>
.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}
</style>
